package com.wcity.manage.service.impl;

import com.wcity.manage.common.context.Constants;
import com.wcity.manage.common.context.ServiceConstants;
import com.wcity.manage.common.utils.Log;
import com.wcity.manage.common.utils.OSSUtil;
import com.wcity.manage.common.utils.SmsUtil;
import com.wcity.manage.common.utils.StringUtil;
import com.wcity.manage.dao.mapper.VerifyMapper;
import com.wcity.manage.dao.model.Verify;
import com.wcity.manage.service.CommentService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Decoder;

import javax.annotation.Resource;
import java.io.*;
import java.util.Arrays;
import java.util.List;

/**
 * @author sxd
 */
@Service("commentService")
public class CommentServiceImpl implements CommentService {

    @Override
    public String uploadPic(MultipartFile picFile) {
        String originalFilename = picFile.getOriginalFilename();
        String picSuffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        if( !ServiceConstants.PICSUFFIXS.contains(picSuffix) ){
            return ServiceConstants.UploadPic.ERROR_FORMAT.code;
        }
        long picSize = picFile.getSize();
        if(picSize > ServiceConstants.PIC_TOP_SIZE){
            return ServiceConstants.UploadPic.ERROR_SIZE.code;
        }
        String fileName = StringUtil.getUUID() + picSuffix;

        try(InputStream input = picFile.getInputStream()){
            String key = OSSUtil.FILEPATH + fileName;
            OSSUtil.uploadFile(input, key, picSize);
            return OSSUtil.OSS_URLPREFIX + "/" + key;
        }catch (final IOException e){
            LOG.error("上传图片到OSS发生异常 ==> " + e.getMessage(), e);
            return ServiceConstants.UploadPic.ERROR_EXCEPTION.code;
        }
    }

    @Override
    public String uploadImageBase64(String imgStr) {

        if ( StringUtil.isBlank( imgStr ) || !imgStr.contains( "data:image/" )
                || !imgStr.contains( ";" ) || !imgStr.contains( "," ) ) return "非法base64字符串";

        // 文件后缀名
        String fileSuffix = imgStr.substring( imgStr.indexOf( "/" ) + 1, imgStr.indexOf( ";" ) );

        // 截取编码部分
        imgStr = imgStr.split( "," )[1];

        BASE64Decoder decoder = new BASE64Decoder();
        try {
            // Base64解码
            byte[] bytes = decoder.decodeBuffer( imgStr );
            for (int i = 0; i < bytes.length; ++i) {
                // 调整异常数据
                if (bytes[i] < 0) bytes[i] += 256;
            }

            InputStream input = new ByteArrayInputStream( bytes );
            String key = OSSUtil.FILEPATH + StringUtil.getUUID() + "." + fileSuffix;

            OSSUtil.uploadFile( input, key, bytes.length );

            return OSSUtil.OSS_URLPREFIX + "/" + key;
        } catch (Exception e) {
            e.printStackTrace();
            return "上传失败";
        }

    }

    @Override
    public String delPic(String url) {

        if ( StringUtil.isBlank( url ) || !url.contains( "http://oss.188jielan.net/images/wcityHz/" ) )
            return "地址为空或者链接不存在";

        try {
            if ( url.contains(",") ) {
                List<String> keys = imageList( url );
                if ( keys != null ) {
                    for ( String key : keys ) {
                        OSSUtil.deleteFile( key.substring( key.indexOf( "images" ) ) );
                    }
                }
            } else {
                OSSUtil.deleteFile( url.substring( url.indexOf( "images" ) ) );
            }
        } catch (Exception e) {
            LOG.error("删除图片异常 ==> " + e.getMessage(), e);
            return "删除图片失败";
        }

        return "";
    }

    @Override
    public List<String> imageList(String url) {

        if ( StringUtil.isBlank( url ) ) return null;

        String[] array = url.split(",");

        if ( array.length <= 0 ) return null;

        return Arrays.asList( array );
    }

    @Override
    public String checkCode(String phone, String code, int type) {

        Verify verify = verifyMapper.find( phone, code, type );

        if ( verify == null || verify.getStatus() == 2 ) return "验证失败";

        long now = System.currentTimeMillis();
        long time = verify.getCreateTime().getTime();
        if ( ( now - time ) > Constants.VERIFY_EXPIRE_TIME ) return "验证码已失效";

        verifyMapper.update( verify.getId() );

        return "";
    }

    @Override
    public String getCode(String phone, int type) {

        verifyMapper.updateCode( phone, type );

        String code = StringUtil.createRandom( true, 6 );

        Verify verify = new Verify();
        verify.setStatus( 1 );
        verify.setCode( code );
        verify.setPhone( phone );
        verify.setType( type );

        try {
            if ( verifyMapper.insert( verify ) <= 0 ) return "获取验证码失败";
        } catch (DataAccessException e) {
            Log.error( "获取验证码失败" );
            return "获取验证码失败";
        }

        SmsUtil.sendSms( phone, "你的验证码是：" + code + "，有效期30分钟。【杭州捷蓝】" );

        return "";
    }

    @Resource private VerifyMapper verifyMapper;

    private static final Logger LOG = LoggerFactory.getLogger(CommentServiceImpl.class);
}
